import React, { Component, useState, useEffect, useRef } from 'react';
import {
  Form,
  Input,
  Table,
  Row,
  Col,
  Button,
  Divider,
  Popconfirm,
  DatePicker,
  Icon,
  Modal,
  Select,
} from 'antd';
const { Option } = Select;
import Add from './add';
import View from './view';
import Edit from './edit';
import { connect } from 'dva';
import moment from 'moment';
import { soldSearch } from '@/services/user';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
const { MonthPicker, RangePicker } = DatePicker;
const Index = ({
  dispatch,
  form,
  dataSource,
  total,
  isRefresh,
  totalbuy,
  dataSourceSale,
  total1,
  totalSale,
}: {
  dispatch: (type: any) => void;
  form: any;
  dataSource: Array<any>;
  total: number;
  isRefresh: boolean;
  totalbuy: any;
  dataSourceSale: any;
  total1: any;
  totalSale: any;
}) => {
  const { getFieldDecorator } = form;

  const [page, setpage] = useState(1);
  const [size, setsize] = useState(10);
  const [pageSale, setpageSale] = useState(1);
  const [sizeSale, setsizeSale] = useState(10);
  // const [startDate, setstartDate] = useState(Number(moment(Date.now()).startOf('day')));
  const [endDate, setendDate] = useState(Number(moment(Date.now()).endOf('day')));
  const [startDate, setstartDate] = useState(0);
  // const [endDate, setendDate] = useState('');
  const [personData, setpersonData] = useState([]);
  const [staffId, setstaffId] = useState('');
  const [addVisible, setaddVisible] = useState(false);
  const [viewVisible, setviewVisible] = useState(false);
  const [editVisible, seteditVisible] = useState(false);
  let addRef: any = useRef(null);
  let viewRef: any = useRef(null);
  let editRef: any = useRef(null);
  const columns: Array<any> = [
    {
      title: '订单号',
      dataIndex: 'id',
      align: 'center',
    },
    {
      title: '订单创建人',
      dataIndex: 'creatorName',
      align: 'center',
    },

    {
      title: '方式',
      dataIndex: 'typeName',
      align: 'center',
    },
    {
      title: '人员',
      dataIndex: 'staffName',
      align: 'center',
    },
    {
      title: '酒类',
      dataIndex: 'wineName',
      align: 'center',
    },
    {
      title: '仓库',
      dataIndex: 'wareHouseCode',
      align: 'center',
    },

    {
      title: '公司核定买入价',
      dataIndex: 'companyPrice',
      align: 'center',
    },
    {
      title: '员工买入单价',
      dataIndex: 'staffPrice',
      align: 'center',
    },
    {
      title: '数量',
      dataIndex: 'quantity',
      align: 'center',
    },
    {
      title: '单位',
      dataIndex: 'quantityComments',
      align: 'center',
    },
    {
      title: '运费',
      dataIndex: 'freight',
      align: 'center',
    },
    {
      title: '其它费用',
      dataIndex: 'otherFee',
      align: 'center',
    },
    {
      title: '其它费用备注',
      dataIndex: 'otherFeeComments',
      align: 'center',
    },
    {
      title: '成交时间',
      dataIndex: 'dealTime',
      align: 'center',
      render: (text: any) => {
        return (
          <>
            <span>{moment(text).format('YYYY-MM-DD HH:mm:ss')}</span>
          </>
        );
      },
    },
    {
      title: '利润比',
      dataIndex: 'companyProfitProportion',
      align: 'center',
      render: (text: any) => {
        return (
          <>
            <span>{1 - Number(text)}</span>
          </>
        );
      },
    },
    {
      title: '员工利润',
      dataIndex: 'staffProfit',
      align: 'center',
    },
    {
      title: '公司利润',
      dataIndex: 'companyProfit',
      align: 'center',
    },
    {
      title: '订单状态',
      dataIndex: 'orderStatus',
      align: 'center',
    },
    {
      title: '操作',
      dataIndex: 'operation',
      render: (text: any) => {
        return (
          <>
            <span
              onClick={() => {
                seteditVisible(true);
              }}
            >
              <a>修改</a>
            </span>
          </>
        );
      },
    },
  ];

  useEffect(() => {
    handleSearchbuy();
  }, [size, page]);

  const handleSearchbuy = () => {
    dispatch({
      type: 'personbuy/list',
      payload: {
        page,
        size,
        startDate,
        endDate,
        staffId,
      },
    });
  };
  const handleReset = () => {
    form.resetFields();
  };
  const handleaddOk = () => {
    // setaddVisible(false);
    addRef.handleSubmit();
  };

  const handleaddCancel = () => {
    setaddVisible(false);
  };
  const handleviewOk = () => {
    setviewVisible(false);
  };

  const handleviewCancel = () => {
    setviewVisible(false);
  };
  const handleeditOk = () => {
    editRef.handleSubmit();
  };

  const handleeditCancel = () => {
    seteditVisible(false);
  };

  return (
    <PageHeaderWrapper>
      <div style={{ padding: '12px 24px', background: '#fff', marginBottom: '6px' }}>
        <Form layout="inline">
          <Form.Item label="员工">
            <Select
              style={{ width: 220 }}
              showSearch
              // value={value}
              placeholder="请输入工作人员"
              // notFoundContent={fetching ? <Spin size="small" /> : null}
              filterOption={false}
              allowClear
              onFocus={() => {
                soldSearch({ comments: '' }).then(res => {
                  if (res.status == 200) {
                    setpersonData(res.data);
                  } else {
                    setpersonData([]);
                  }
                });
              }}
              onSearch={value => {
                soldSearch({ comments: value }).then(res => {
                  if (res.status == 200) {
                    setpersonData(res.data);
                  } else {
                    setpersonData([]);
                  }
                });
              }}
              onChange={(val: any) => {
                console.log(val, 8888);
                setstaffId(val);
              }}
            >
              {personData.length > 0
                ? personData.map((item: any, index) => (
                    <Option key={item.id}>
                      {item.name}({item.phoneNumber})
                    </Option>
                  ))
                : null}
            </Select>
          </Form.Item>
          <Form.Item label="时间">
            {getFieldDecorator(
              'staffId',
              {},
            )(
              <RangePicker
                ranges={{
                  今日: [moment(), moment()],
                  当月: [moment().startOf('month'), moment().endOf('month')],
                }}
                format="YYYY/MM/DD"
                onChange={([start, end]) => {
                  setstartDate(Number(start));
                  setendDate(Number(end));
                }}
              />,
            )}
          </Form.Item>
          <Form.Item>
            <Button
              type="primary"
              onClick={() => {
                handleSearchbuy();
                // handleSearchsale();
              }}
              style={{ marginRight: '14px' }}
            >
              搜索
            </Button>
          </Form.Item>
        </Form>
      </div>
      <div style={{ height: '28px', margin: '4px 0', padding: '0 8px', overflow: 'hidden' }}>
        <div style={{ minWidth: '140px', float: 'right' }}>总利润：{totalbuy.totalProfits}</div>
        <div style={{ minWidth: '120px', float: 'right' }}>总订单数：{total}</div>
      </div>
      <Row>
        <Table
          bordered
          columns={columns}
          loading={isRefresh}
          dataSource={dataSource}
          size="middle"
          pagination={{
            pageSize: size,
            showSizeChanger: true,
            pageSizeOptions: ['5', '10', '20', '30'],
            showQuickJumper: true,
            current: page,
            total: total,
            onChange: (page: any, pageSize: any) => {
              setpage(page);
            },
            onShowSizeChange: (current: any, size: any) => {
              setsize(size);
            },
          }}
        />
      </Row>
      <Modal
        title="新增"
        visible={addVisible}
        destroyOnClose
        width={550}
        onOk={handleaddOk}
        onCancel={handleaddCancel}
      >
        <Add
          close={() => {
            setaddVisible(false);
          }}
          submit={(view: any, data: any) => {
            dispatch({
              type: 'dict/add',
              payload: data,
            });
          }}
          wrappedComponentRef={(form: any) => {
            addRef = form;
          }}
        />
      </Modal>
      <Modal
        title="查看"
        width={840}
        destroyOnClose
        visible={viewVisible}
        onOk={handleviewOk}
        onCancel={handleviewCancel}
      >
        <View
          close={() => {
            setviewVisible(false);
          }}
          wrappedComponentRef={(form: any) => {
            viewRef = form;
          }}
        />
      </Modal>
      <Modal
        title="修改"
        width={980}
        destroyOnClose
        centered
        visible={editVisible}
        onOk={handleeditOk}
        onCancel={handleeditCancel}
      >
        <Edit
          close={() => {
            seteditVisible(false);
          }}
          submit={(view: any, data: any) => {
            console.log(data, 9999);
            dispatch({
              type: 'dict/edit',
              payload: { ...view, ...data },
            });
          }}
          wrappedComponentRef={(form: any) => {
            editRef = form;
          }}
        />
      </Modal>
    </PageHeaderWrapper>
  );
};

export default connect(({ personbuy, personsale }: any) => ({
  dataSource: personbuy.list,
  total: personbuy.total,
  totalbuy: personbuy.totalprofit,
  dataSourceSale: personsale.list,
  total1: personsale.total,
  totalSale: personsale.totalprofit,
}))(Form.create()(Index));
